package wordEvo.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import whipstaff.wordevo.data.Result;

/**
 * @author Jim Buck, Whipstaff Productions
 * @since August 10, 2011
 * @updated August 23, 2011
 */
public class RecieveThread extends Thread
{
	private ObjectInputStream inStream;
	private EvoServer parent;
	private Socket client;
	
	private Result result;
		
	public RecieveThread(EvoServer evo) {
		super("EvoRecieveThread");
		this.parent = evo;
		this.client = evo.getSocket();
	}
	
	@Override
	public void run() {
		System.out.println("Connection made...");
		initThread();
		if(this.inStream != null)
		{
			recieve();
			this.parent.submitResult(this.result);
		}
		closeConnection();
	}
	// Initializes the necessary variables.
	private void initThread() {
		try {	
			this.result = null;
			this.inStream = new ObjectInputStream(this.client.getInputStream());
		} catch (IOException e) {
			System.err.println("There was a problem catching the input stream. (Might be test connection.)");
		}
	}
	// Receives the Result from the client.
	private void recieve() {
		try {				
			this.result = (Result) inStream.readObject();
			System.out.println("Result recieved(" + this.result + ")");
		} catch (IOException e) {
			System.err.println("ERROR: There was a problem reading the input stream.");
			e.printStackTrace();
			System.exit(1);
		} catch (ClassNotFoundException e) {
			System.err.println("ERROR: There was a problem decyphering the Result.");
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	// Flushes the object streams and closes the connections.
	private void closeConnection() {
		try {
			this.client.shutdownInput();
			this.client.shutdownOutput();
			this.client.close();
		} catch (IOException e) {
			System.err.println("ERROR: There was a problem closing the sockets.");
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	@Override
	public String toString() {
		return this.getName() + " [" + this.getId() + "] : " + this.getState();
	}
}